//
//  YBCodeMenuController.m
//  Cocoachina
//
//  Created by 游兵 on 2017/9/15.
//  Copyright © 2017年 YBing. All rights reserved.
//

#import "YBCodeMenuController.h"
#import "YBCodeTagCell.h"

@interface YBCodeMenuController ()

@property (nonatomic, strong) NSArray<YBCodeTag *> *tags;

@end

@implementation YBCodeMenuController

- (void)setDoc:(TFHpple *)doc
{
    _doc = doc;
    self.tags = [self parseWithHpple:doc];
    [self.tableView reloadData];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (NSMutableArray<YBCodeTag *> *)parseWithHpple:(TFHpple *)doc
{
    TFHppleElement *categorylist = [[doc searchWithXPathQuery:@"//div[@class='categorylist']"] firstObject];
    NSArray<TFHppleElement *> *show = [[categorylist firstChildWithClassName:@"show"] childrenWithTagName:@"li"];
    NSArray<TFHppleElement *> *more = [[categorylist firstChildWithClassName:@"more"] childrenWithTagName:@"li"];
    NSArray<TFHppleElement *> *list = [show arrayByAddingObjectsFromArray:more];
    NSMutableArray<YBCodeTag *> *tags = [NSMutableArray array];
    YBCodeTag *tag = [YBCodeTag new];
    tag.url = @"http://code.cocoachina.com/";
    tag.zh = @"最新";
    tag.en = @"";
    tag.num = @"";
    [tags addObject:tag];
    
    [list enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YBCodeTag *tag = [YBCodeTag new];
        TFHppleElement *a = [obj firstChildWithTagName:@"a"];
        tag.url = [a objectForKey:@"href"];
        tag.zh = [a firstChildWithClassName:@"zh"].text;
        tag.en = [a firstChildWithClassName:@"en"].text;
        tag.num = [a firstChildWithClassName:@"cnt"].text;
        [tags addObject:tag];
    }];
    return tags;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tags.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBCodeTagCell *cell = [[YBCodeTagCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@""];
    cell.codeTag = self.tags[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.didSelectedBlock) {
        self.didSelectedBlock(self.tags[indexPath.row]);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

@end
